package com.gvsoft.communication.common.model.packet;

import com.gvsoft.communication.net.model.IPacket;

/**
 * Created with IntelliJ IDEA.
 * ProjectName:gvMsgRouting
 * Author: zhaoqiubo
 * Date: 15/8/7
 * Time: 下午3:19
 * Desc: 从客户端接收的报文抽象类
 */
public  class Packet implements IPacket{

    /**
     * 报文区间分隔符，报文分为三个区间，HEADER区间、RID区间、BODY区间；
     * HEADER标记报文分类，RID为报文对象id，在一定周期内唯一；BODY为报文的内容区域。
     */
    public static String HBREGEX = "|";
    String header;
    String rid;
    String clientToken;
    String packetBody;

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }

    public String getRid() {
        return rid;
    }

    public void setRid(String rid) {
        this.rid = rid;
    }

    public String getClientToken() {
        return clientToken;
    }

    public String getPacketBody() {
        return packetBody;
    }

    public void generatePacket(String header, String rid, String clientToken, String packetBody) {
        this.header = header;
        this.packetBody = packetBody;
        this.rid = rid;
        this.clientToken = clientToken;
    }
    public void generatePacket(String header, String rid) {
        this.header = header;
        this.rid = rid;
    }

    public void generatePacket(String header, String rid, String clientToken) {
        this.header = header;
        this.rid = rid;
        this.clientToken = clientToken;
    }

    /**
     * 拆分字符串生成packet对象
     * @param strA 消息字符串
     * @return 返回packet对象
     */
    public static IPacket analysePacket(String strA) {

        int posA = strA.indexOf(HBREGEX);
        if (posA > 0) {
            Packet ap = new Packet();
            String strB = strA.substring(posA + 1);
            int posB = strB.indexOf(HBREGEX);
            if (posB > 0) {
                String strC = strB.substring(posB+1);
                int posC = strC.indexOf(HBREGEX);
                if(posC >0) {
                    ap.generatePacket(strA.substring(0, posA), strB.substring(0, posB),
                            strC.substring(0, posC), strC.substring(posC + 1));
                    return ap;
                }
                ap.generatePacket(strA.substring(0, posA), strB.substring(0, posB), strB.substring(posB + 1));
                return ap;
            }else{
                ap.generatePacket(strA.substring(0,posA),strB.substring(posB+1));
                return ap;
            }
        } else {
            return null;
        }
    }

    public static void  main(String[] arg){
        analysePacket("R|5dd3241e656c4349a768e3b9a9e75c1c");

    }
}
